<!--
 * @Description: 创建博文页面
 * @Author: 梁晓雨
 * @Date: 2025-02-06 17:30:22
-->
<template>
    <el-scrollbar height="100%" style="width: 100%;">
        <div class="BlogEditor">
            <div class="BlogEditorChange">
                <el-button type="primary" text @click="toblogEditorWeb">富文本编辑器</el-button>
                <el-button type="primary" text @click="toblogEditorMarkdown">MarkDown编辑器</el-button>
            </div>
            <div style="width: 80%;margin-top: 1%;">
                <el-input placeholder="请输入博文标题" v-model="valueBlogTitle" style="width: 100%;"></el-input>
            </div>
            <div class="editor-body">
                <BlogEditorWeb ref="BlogEditorWebRef" v-if="blogEditorWebStatus"></BlogEditorWeb>
                <BlogEditorMarkdown ref="BlogEditorMarkdownRef" v-if="blogEditorMarkdownStatus"></BlogEditorMarkdown>
            </div>
            <div class="ai-function">
                <div class="ai-function-button">
                    <div>
                        <el-button type="primary" @click="textToImage">文生图</el-button>
                    </div>
                    <div>
                        <el-button type="primary" @click="oneBondGeneration">AI一键生成</el-button>
                        <el-button type="primary" @click="correctMisspellings">错别字纠正</el-button>
                        <el-button type="primary" @click="textPolishing">文本润色</el-button>
                    </div>
                </div>
                <el-card style="max-width: 480px">
                    <template #header>您的博文图片请收好✨🥺</template>
                    <div class="demo-image__error">
                        <div class="block">
                            <el-image :src="textToImageSrc">
                                <template #error>
                                    <div class="image-slot">
                                        <el-icon><icon-picture /></el-icon>
                                    </div>
                                </template>
                            </el-image>
                        </div>
                    </div>
                </el-card>

            </div>
            <div class="ai-summary">
                <el-button type="primary" @click="fullTextSummary">文本总结</el-button>
                <el-input placeholder="全文摘要" v-model="valueAISummary" :rows="3" type="textarea"></el-input>
            </div>
            <div class="select-directory">
                <el-text style="width: 80px;">目录</el-text>
                <el-select v-model="valueDirectory" placeholder="请选择目录" @change="getTagsByDirectoryid"
                    style="width: 200px;" clearable>
                    <el-option v-for="item in optionsDirectory" :key="item.directoryid" :label="item.directoryname"
                        :value="item.directoryid"></el-option>
                </el-select>
            </div>
            <div class="select-tag">
                <el-text style="width: 80px;">标签</el-text>
                <el-select v-model="valueTag" placeholder="请添加标签" style="width: 500px;" clearable multiple collapse-tags
                    popper-class="custom-header" :max-collapse-tags="10" @change="{
                        console.log(valueTag);
                    }">
                    <el-option v-for="item in optionsTag" :key="item.tagid" :label="item.tagname"
                        :value="item.tagid"></el-option>
                </el-select>
            </div>
            <div class="operation-button">
                <el-button type="primary" @click="submitBlog">发布</el-button>
            </div>
            <div style="height: 100px;"></div>
        </div>

    </el-scrollbar>

</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import BlogEditorWeb from "../../../components/BlogEditorWeb/BlogEditorWeb.vue";
import BlogEditorMarkdown from "../../../components/BlogEditorMarkdown/BlogEditorMarkdown.vue";
import request from "@/utils/request";
import { ElMessage } from "element-plus";
import store from "@/store";
import { Picture as IconPicture } from '@element-plus/icons-vue'
import NumArraytoString from "@/utils/NumArraytoString";
import StrArraytoString from "@/utils/StrArraytoString";
import router from "@/router";


// 控制编辑器显示的种类
const blogEditorWebStatus = ref(true)
const blogEditorMarkdownStatus = ref(false)

// 文生图图片
const textToImageSrc = ref('')
// 博文标题
const valueBlogTitle = ref('')
// 智能总结
const valueEditor = ref('')  // 编辑器内容
const valueAISummary = ref('')  // AI摘要内容
const BlogEditorWebRef = ref(null)
const BlogEditorMarkdownRef = ref(null)
// 目录
interface Directorys {
    userid: number,
    directoryid: number,
    directoryname: string,
    isDeletedDirectory: string
}
// 当前目录
const valueDirectory = ref<number | null>(null)
// 目录列表
const optionsDirectory = ref<Directorys[]>([])
// 标签
interface Tag {
    tagid: number,
    directoryid: number,
    tagname: string,
    isDeletedTag: number
}
// 当前的标签们
const valueTag = ref<number[] | null>(null)
// 标签列表
const optionsTag = ref<Tag[]>([])



/**
 * @description: 将编辑器切换成富文本编辑器
 * @return {*}
 * @Author: 梁晓雨
 * @Date: 2025-03-03 22:40:59
 */
const toblogEditorWeb = () => {
    blogEditorWebStatus.value = true
    blogEditorMarkdownStatus.value = false
}
/**
 * @description: 将编辑器切换成Markdown编辑器
 * @return {*}
 * @Author: 梁晓雨
 * @Date: 2025-03-03 22:41:20
 */
const toblogEditorMarkdown = () => {
    blogEditorWebStatus.value = false
    blogEditorMarkdownStatus.value = true
}
/**
 * @description: ai智能总结函数(已废弃)
 * @Author: 梁晓雨
 * @Date: 2025-03-03 21:48:13
 */
const aiSummary = async () => {
    const content = returnEditorContentText();

    const msg = content + "       请你为以上的内容生成摘要，不超过100字。";
    console.log(msg);

    await request.post('/chatAi/chat?msg=' + msg)
        .then(res => {
            valueAISummary.value = res.result;
            ElMessage({
                message: '智能总结成功',
                type: 'success'
            })
        })
        .catch(error => {
            ElMessage({
                message: '服务器可能繁忙，稍后再试',
                type: 'error'
            })
        })

}

/**
 * @description: 调用子组件返回编辑器内容
 * @return {*} null 
 * @Author: 梁晓雨
 * @Date: 2025-03-03 21:49:14
 * @param {*} string 编辑器内容
 */
const returnEditorContent = (): string => {
    const editorContent = ref('')
    if (blogEditorWebStatus.value && BlogEditorWebRef.value) {
        editorContent.value = BlogEditorWebRef.value.returnContent(); // 调用Web编辑器的returnContent方法
    } else if (blogEditorMarkdownStatus.value && BlogEditorMarkdownRef.value) {
        editorContent.value = BlogEditorMarkdownRef.value.returnContent(); // 调用Markdown编辑器的returnContent方法
    }

    valueEditor.value = editorContent.value;
    return editorContent.value;
};

/**
 * @description: 调用子组件返回编辑器的纯文本内容
 * @return {*}
 * @Author: 梁晓雨
 * @Date: 2025-03-03 21:49:59
 * @param {*} string 编辑器纯文本内容
 */
const returnEditorContentText = (): string => {
    const editorContent = ref('')
    if (blogEditorWebStatus.value && BlogEditorWebRef.value) {
        // 如果当前是富文本编辑器
        editorContent.value = BlogEditorWebRef.value.returnContentText(); // 调用Web编辑器的returnContent方法
    } else if (blogEditorMarkdownStatus.value && BlogEditorMarkdownRef.value) {
        // 如果当前是Markdown编辑器
        editorContent.value = BlogEditorMarkdownRef.value.returnContentText(); // 调用Markdown编辑器的returnContent方法
    }

    return editorContent.value;
};



/**
 * @description: 通过目录id获取标签
 * @return {*}
 * @Author: 梁晓雨
 * @Date: 2025-03-03 22:40:31
 */
const getTagsByDirectoryid = async () => {
    await request.get('/tag/queryAll', {
        params: {
            directoryid: valueDirectory.value
        }
    }).then(res => {
        optionsTag.value = res.data
    })
}

// 保存博客
const submitBlog = async () => {
    returnEditorContent();
    const userId = store.getters.getUser.userId;
    const now = new Date();
    const currentTime = now.toLocaleString();
    const originalBlogId = -1;  // 原创博文

    const currentTagsName: string[] = optionsTag.value
        .filter(tag => valueTag.value?.includes(tag.tagid))
        .map(tag => tag.tagname)
    const currentTagsIdStr = NumArraytoString(valueTag.value)
    const currentTagsNameStr = StrArraytoString(currentTagsName)


    // 保存博文
    await request.post('/blog/add', {
        blogid: null,
        userid: userId,
        blogTitle: valueBlogTitle.value,
        aiSummary: valueAISummary.value,
        blogText: valueEditor.value,
        blogPhotoSrc: textToImageSrc.value,
        directoryId: valueDirectory.value,
        directoryName: optionsDirectory.value.find( item => item.directoryid == valueDirectory.value )?.directoryname,
        directorySrc: textToImageSrc.value,
        blogUpdated: currentTime,
        tagId: currentTagsIdStr,
        tagName: currentTagsNameStr,
        originalBlogId: originalBlogId,  // 因为在创建博客页面中必然是原创博文，所以直接赋值为1
        isDeletedBlog: 0
    }).then(res => {
        ElMessage({
            message: '发布博文成功',
            type: 'success'
        })
    }).catch(error => {
        ElMessage({
            message: '发布博文失败',
            type: 'error'
        })
    })

    router.push('/blogHomePage')
}
/**
 * @description: 文生图
 * @return {*} 文生图的图片链接
 * @Author: 梁晓雨
 * @Date: 2025-03-03 22:04:37
 */
const textToImage = async () => {
    const text = returnEditorContentText();
    try {
        await request.get('/chatCoze/textToImage', {
            params: {
                text: text
            }
        }).then(res => {
            textToImageSrc.value = res.data
        })
        ElMessage({
            message: '文生图成功',
            type: 'success'
        })
    } catch (error) {
        ElMessage({
            message: '文生图失败',
            type: 'error'
        })
    }
}
/**
 * @description: 文本润色
 * @return {*} 润色后文本
 * @Author: 梁晓雨
 * @Date: 2025-03-03 22:08:19
 */
const textPolishing = async () => {
    const text = returnEditorContentText();
    try {
        await request.get('/chatCoze/textPolishing', {
            params: {
                text: text
            }
        }).then(res => {
            //  重置编辑器内容
            if (blogEditorWebStatus.value && BlogEditorWebRef.value) {
                // 如果当前是富文本编辑器
                BlogEditorWebRef.value.contentChange(res.data);
            } else if (blogEditorMarkdownStatus.value && BlogEditorMarkdownRef.value) {
                // 如果当前是Markdown编辑器
                BlogEditorMarkdownRef.value.contentChange(res.data);
            }

            ElMessage({
                message: '文本润色成功',
                type: 'success'
            })
        })
    } catch (error) {
        ElMessage({
            message: '文本润色失败',
            type: 'error'
        })
    }
}
/**
 * @description: 对编辑器内容进行错别字纠正
 * @return {*}
 * @Author: 梁晓雨
 * @Date: 2025-03-03 22:45:34
 */
const correctMisspellings = async () => {
    const text = returnEditorContentText();

    try {
        await request.get('/chatCoze/correctMisspellings', {
            params: {
                text: text
            }
        }).then(res => {
            //  重置编辑器内容
            if (blogEditorWebStatus.value && BlogEditorWebRef.value) {
                // 如果当前是富文本编辑器
                BlogEditorWebRef.value.contentChange(res.data);
            } else if (blogEditorMarkdownStatus.value && BlogEditorMarkdownRef.value) {
                // 如果当前是Markdown编辑器
                BlogEditorMarkdownRef.value.contentChange(res.data);
            }

        })

        ElMessage({
            message: '错别字纠正成功',
            type: 'success'
        })
    } catch (error) {
        ElMessage({
            message: '错别字纠正失败',
            type: 'error'
        })
    }
}
/**
 * @description: 对编辑器的内容进行智能总结
 * @return {*}
 * @Author: 梁晓雨
 * @Date: 2025-03-03 22:48:18
 */
const fullTextSummary = async () => {
    const text = returnEditorContentText();
    try {
        await request.get('/chatCoze/fullTextSummary', {
            params: {
                text: text
            }
        }).then(res => {
            // 重置文本摘要输入框的内容
            valueAISummary.value = res.data
        })

        ElMessage({
            message: '智能总结成功',
            type: 'success'
        })
    } catch (error) {
        ElMessage({
            message: '智能总结失败',
            type: 'error'
        })
    }
}

/**
 * @description: 一键进行文生图、智能总结、错别字纠正和文本润色
 * @return {*}
 * @Author: 梁晓雨
 * @Date: 2025-03-03 22:49:35
 */
const oneBondGeneration = async () => {
    try {
        await textToImage()
        await textPolishing()
        await fullTextSummary()
        await correctMisspellings()

    } catch (error) {
        console.log(error);

    }
}

// 初始执行
onMounted(
    async () => {
        await request.get('/directory/queryAll', {})
            .then(res => {
                optionsDirectory.value = res.data
            })
    }
)
</script>
<style scoped lang="scss">
@use './BlogCreatePost.scss';
</style>
